package com.cy.store.controller;

import com.cy.store.controller.ex.*;
import com.cy.store.service.ex.*;
import com.cy.store.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/*控制层的基类*/
public class BaseController {

    /*表述操作成功的状态码*/
    public static final int OK = 200;

    //请求处理方法，这个方法的防护值就是需要传递的给全端的数据
    //自动将异常对象传递给此方法的参数列表上
    //当前项目中产生了异常，被统一拦截到此方法中，这个方法此时就冲当的是请求处理方法，方法的返回值直接给到前端
    @ExceptionHandler({ServiceException.class,FileUploadException.class}) //用于统一处理抛出的异常
    public JsonResult<Void>handleException(Throwable e)
    {
        JsonResult<Void> result = new JsonResult<>(e);
        if (e instanceof UsernameDuplicatedException)
        {
            result.setState(4000);
            result.setMessage("用户名已被占用");
        }else if (e instanceof AddressNotFoundException)
        {
            result.setState(4001);
            result.setMessage("用户的收货地址数据不存在的异常");
        }else if (e instanceof AccessDeniedException)
        {
            result.setState(4002);
            result.setMessage("收货地址数据非法访问的异常");
        }else if (e instanceof UserNotFoundException)
        {
            result.setState(5001);
            result.setMessage("用户数据不存在");
        }else if (e instanceof PasswordNotMatchException)
        {
            result.setState(5002);
            result.setMessage("用户密码错误");
        }
        else if (e instanceof InsertExcption)
        {
            result.setState(5000);
            result.setMessage("注册时产生未知的异常");
        }else if (e instanceof Updateexception)
        {
            result.setState(5001);
            result.setMessage("更新数据时产生未知的异常");
        }else if (e instanceof FileEmptyException) {
            result.setState(6000);
        } else if (e instanceof FileSizeException) {
            result.setState(6001);
        } else if (e instanceof FileTypeException) {
            result.setState(6002);
        } else if (e instanceof FileStateException) {
            result.setState(6003);
        } else if (e instanceof FileUploadIOException) {
            result.setState(6004);
        }
        return result;
    }


    //获取session对象中的uid
    protected  final Integer getuidFromSession(HttpSession session)
    {
        return Integer.valueOf(session.getAttribute("uid").toString());
    }
    protected final String getUsernameFromSession(HttpSession session)
    {
        return session.getAttribute("username").toString();
    }
}
